package cn.pconline.officialclub.web;

import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ActivityService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.Result;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OActivityMember;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OCommonMember;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.ODynaService;
import cn.pconline.officialclub.service.OMessageService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 官方活动相关
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/brand/activity")
public class OActivityController extends WebKit {

    @Autowired
    private OActivityService oActivityService;
    @Autowired
    private OClubService oClubService;
    @Autowired
    private ODynaService oDynaService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private DynaService dynaService;
    @Autowired
    private OMessageService oMessageService;
    //活动创建默认封面图
    private static final String defalutImg = "http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto8.jpg";

    /**
     * 活动创建页面跳转
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/createActivityPage.do", method = RequestMethod.GET)
    public String createActivityPage(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            try {
                resp.sendError(404);
            } catch (IOException ex) {
                Logger.getLogger(OActivityController.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
        User user = userAuth.getUser(req, resp);
        if (!isAdmin(req, resp)) {
            return PAGE_NO_AUTH;
        }
        OActivity activity = null;
        String coverImg = defalutImg;
        boolean isEditTime = false;
        if (activityId > 0) {
            activity = oActivityService.findById(OActivity.class, activityId);
            if (activity == null) {
                return redirect404(resp);
            } else {
                if (StringUtils.isNotBlank(activity.getPicUrl())) {
                    coverImg = activity.getPicUrl();
                }
                if (activity.getLongContent() > 0) {
                    activity.setContent(oActivityService.getActivityContent(activityId));
                }
                if (activity.getEndDate().getTime() < DateUtils.getNow().getTime()) {
                    isEditTime = true;
                }
            }
        }
        req.setAttribute("user", user);
        req.setAttribute("coverImg", coverImg);
        req.setAttribute("oClub", oClub);
        req.setAttribute("activity", activity);
        req.setAttribute("isEditTime", isEditTime);
        return "template/official/pc/activity/activityAdd";
    }

    /**
     * 活动创建
     *
     * @param req
     */
    @RequestMapping(value = "/createActivity.do", method = RequestMethod.POST)
    public void createActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        String picUrl = WebUtils.param(req, "picUrlOrigin", "");
        int picWidth = WebUtils.paramInt(req, "picWidth", 0);
        int picHeight = WebUtils.paramInt(req, "picHeight", 0);
        if (!isAdmin(req, resp)) {
            printMsg(resp, Result.dataError("没有权限"));
            return;
        }
        OActivity activity = this.convertActivity(req);
        //表单验证
        if (this.checkActivity(activity, resp)) {
            activity.setCreateAt(DateUtils.getNow());
            User user = userAuth.getUser(req, resp);
            activity.setCreateBy(user.getUid());
            if (activity.getActivityId() > 0) {
                //update
                oActivityService.updateActivity(activity);
            } else {
                //add
                activity.setStatus(OActivity.STATUS_YES);
                oActivityService.createActivity(activity);
                if (activity.getActivityId() > 0) {
                    //发布活动动态 不需要同步到民间车友会
                    AbstractDyna dyna = new AbstractDyna();
                    dyna.setContent("");//内容直接拿活动信息，这里不需要设置
                    dyna.setCreateBy(activity.getCreateBy());
                    dyna.setCreateName(user.getNickname());
                    dyna.setCreateDate(activity.getCreateAt());
                    dyna.setTargetId(activity.getActivityId());
                    List<DynaImage> img = new ArrayList<DynaImage>();
                    if (StringUtils.isNotBlank(picUrl) && picWidth > 0 && picHeight > 0) {
                        DynaImage i = new DynaImage();
                        i.setUrl(picUrl);
                        i.setHeight(picHeight);
                        i.setWidth(picWidth);
                        i.setSeq(1);
                        img.add(i);
                    }
                    oDynaService.createActivityDyna(dyna, oClubId, img);
                }
            }
            printMsg(resp, Result.success(Result.instance().set("activityId", activity.getActivityId())));
        }
    }

    /**
     * 活动列表
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/activityList.do", method = RequestMethod.GET)
    public String activityList(HttpServletRequest req, HttpServletResponse resp) {
        long oClubId = WebUtils.paramOClubId(req);
        int pageNo = WebUtils.paramInt(req, "pageNo", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 10, DEF_MIN_PAGESIZE, DEF_MAX_PAGESIZE);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return redirect404(resp);
        }
        User user = userAuth.getUser(req, resp);
        if (user.getUid() > 0) {
            OCommonMember member = oMemberService.findCommonMember(user.getUid(), oClubId);
            req.setAttribute("member", member);
        }
        Pager<OActivity> listActivity = oActivityService.pageActivityBy(user.getUid(), oClubId, false, pageNo, pageSize);
        req.setAttribute("oClub", oClub);
        req.setAttribute("pager", listActivity);
        req.setAttribute("user", user);
        req.setAttribute("oClub", oClub);

        return "template/official/pc/activity/officialActivityList";
    }

    /**
     * 活动详情
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/activityDetail.do", method = RequestMethod.GET)
    public String activityDetail(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long oClubId = WebUtils.paramOClubId(req);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return redirect404(resp);
        }
        OActivity activity = oActivityService.findValidActivity(activityId);
        User user = userAuth.getUser(req, resp);
        if (activity == null) {
            return redirect404(resp);
        }
        if (user.getUid()>0) {
            OCommonMember member = oMemberService.findCommonMember(user.getUid(), oClubId);
            if (member != null) {
                req.setAttribute("member", member);
            }
            req.setAttribute("user", user);
        }
        //完整内容
        if (activity != null) {
            if (activity.getLongContent() == OActivity.HAS_LONGCONTENT) {
                activity.setFullContent(oActivityService.getActivityContent(activityId));
            } else {
                activity.setFullContent(activity.getContent());
            }
        }
        if (user != null) {
            activity.setUserActivityStatus(oActivityService.getActivityStatusDesc(user.getUid(), activity).getString("activityCode"));
        }
        int isSignUp = 0;//是否报名
        if (user != null && oClubId > 0) {
            if (oActivityService.findActivityMember(activityId, user.getUid()) != null) {
                isSignUp = 1;
            }
        }
        //该活动参加的人员列表
        List<OActivityMember> listMember = oActivityService.listMember(activityId, OActivityMember.STATUS_PASS);
        List<OActivityMember> listApply = oActivityService.listMember(activityId, OActivityMember.STATUS_APPLY);
        req.setAttribute("user", user);
        req.setAttribute("isUserLock", oMemberService.isUserLock(user, oClubId));
        req.setAttribute("isSignUp", isSignUp);
        req.setAttribute("oClubId", oClubId);
        req.setAttribute("oClub", oClub);
        req.setAttribute("activity", activity);
        req.setAttribute("listMember", listMember);
        req.setAttribute("listApply", listApply);
        return "template/official/pc/activity/activityDetail";
    }

    /**
     * 活动报名页跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/activityApply.do", method = RequestMethod.GET)
    public String activityApply(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        req.setAttribute("activityId", activityId);
        return getPcTemplPath("/activity/activityApply");
    }

    /**
     * 活动报名审核——通过
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/passApply.do", method = RequestMethod.POST)
    public void passApply(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long applyId = WebUtils.paramLong(req, "applyId", 0);
        OActivityMember activityMember = oActivityService.findById(OActivityMember.class, applyId);
        if (activityMember == null) {
            printMsg(resp, Result.dataError("该申请不存在"));
            return;
        }
        if (activityMember.getStatus() != OActivityMember.STATUS_APPLY) {
            printMsg(resp, Result.dataError("该申请已被处理"));
            return;
        }
        OActivity oActivity = oActivityService.findValidActivity(activityMember.getActivityId());
        if (oActivity == null) {
            printMsg(resp, Result.dataError("该活动不存在"));
            return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        OCommonMember oCommonMember = oMemberService.findCommonMember(user.getUid(), oActivity.getoClubId());
        if (!isAdmin(req, resp, oCommonMember)) {
            return;
        }
        if ((oActivity.getMaxJoin() > 0 && oActivity.getMaxJoin() < (oActivity.getJoinNum() + activityMember.getJoinNum()))) {
            printMsg(resp, Result.dataError("审核失败，人数超过上限"));
            return;
        }
        oActivityService.passApply(activityMember);
        OClub club = oClubService.findValidClub(oActivity.getoClubId());
        String activityUrl = oMessageService.getOActivityLink(club.getUrl(), oActivity.getActivityId(), oActivity.getTitle());
        //给申请人发送审核通过消息
        oMessageService.sendSysMsg(activityMember.getUserId(), OMessageService.ACTIVITY_APPLY_PASS, activityUrl);
        //给普通车友会发动态通知
        ClubMember mem = memberService.findClubMemberByUserId(activityMember.getUserId());
        if (mem != null) {
            //发布参加活动的动态
            AbstractDyna dyna = new AbstractDyna();
            dyna.setContent("");//内容直接拿活动信息，这里不需要设置
            dyna.setCreateBy(mem.getUid());
            User u = userService.findUser(mem.getUid());
            dyna.setCreateName(u.getNickname());
            dyna.setCreateDate(new Date());//当前时间
            dyna.setTargetId(oActivity.getActivityId());
            dyna.setClubId(mem.getClubId());//同步到普通车友会
            dynaService.createJoinActivityDyna(dyna);
        }
        printMsg(resp, Result.success("审核成功"));
    }

    /**
     * 活动报名审核——拒绝
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/rejectApply.do", method = RequestMethod.POST)
    public void rejectApply(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long applyId = WebUtils.paramLong(req, "applyId", 0);
        OActivityMember activityMember = oActivityService.findById(OActivityMember.class, applyId);
        if (activityMember == null) {
            printMsg(resp, Result.dataError("该申请不存在"));
            return;
        }
        OActivity oActivity = oActivityService.findValidActivity(activityMember.getActivityId());
        if (oActivity == null) {
            printMsg(resp, Result.dataError("该活动不存在"));
            return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        OCommonMember oCommonMember = oMemberService.findCommonMember(user.getUid(), oActivity.getoClubId());
        if (!isAdmin(req, resp, oCommonMember)) {
            return;
        }
        if (activityMember.getStatus() != OActivityMember.STATUS_APPLY) {
            printMsg(resp, Result.dataError("该申请已被处理"));
            return;
        }
        oActivityService.rejectApply(activityMember);
        OClub club = oClubService.findValidClub(oActivity.getoClubId());
        String activityUrl = oMessageService.getOActivityLink(club.getUrl(), oActivity.getActivityId(), oActivity.getTitle());
        //给申请人发送审核通过消息
        oMessageService.sendSysMsg(activityMember.getUserId(), OMessageService.ACTIVITY_APPLY_REJECT, activityUrl);
        printMsg(resp, Result.success("操作成功"));
    }

    /**
     * 删除活动
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/deleteActivity.do", method = RequestMethod.POST)
    public void deleteActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        if (activityId < 1) {
            printMsg(resp, Result.dataError());
            return;
        }
        if (!isAdmin(req, resp)) {
            return;
        }
        OActivity activity = oActivityService.findValidActivity(activityId);
        if(activity == null){
            printMsg(resp,Result.error("活动不存在"));
            return;
        }
        if (oActivityService.removeActivity(activity)) {
            //删除活动对应的动态
        	DynaInfo dynaInfo = dynaService.getDynaByTargetId(activity.getCreateAt(),activityId,DynaInfo.TYPE_ACTIVITY);
        	if(dynaInfo != null) {
        		oDynaService.deleteClubDyna(activity.getoClubId(), dynaInfo.getDynaInfoId());//删除车友会动态索引
                        dynaService.deleteUserDyna(activity.getCreateBy(), dynaInfo.getDynaInfoId());//活动终端都删除了，其他也要删除，不然有脏数据
        	}
            printMsg(resp, Result.success());
        } else {
            printMsg(resp, Result.error("删除失败"));
        }
    }

    /**
     * 报名活动
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/applyActivity.do", method = RequestMethod.POST)
    public void applyActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        OActivity activity = oActivityService.findById(OActivity.class, activityId);
        if (activity == null) {
            printMsg(resp, Result.dataError("活动不存在"));
            return;
        }
        OClub oClub = oClubService.findValidClub(activity.getOClubId());
        if(oClub == null){
             printMsg(resp, Result.error("该车友会不存在"));
             return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        OCommonMember oCommonMember = oMemberService.findCommonMember(user.getUid(), activity.getoClubId());
        if (oCommonMember == null) {
            printMsg(resp, Result.error("您不是该车友会会员"));
            return;
        }
        if(oClub.isMustBindPhone() && StringUtils.isBlank(user.getBindPhone())){
            printMsg(resp, Result.noPermission("您还没有绑定手机,该车友会只有绑定手机后才能互动,请到个人中心绑定手机号码"));
            return;
        }
         if(oMemberService.isUserLock(user,activity.getoClubId())){
            printMsg(resp, Result.noPermission("您所绑定的手机号码已经被该车友会封锁,请在个人中心更改绑定的手机号码！"));
            return;
        }
        String message = "报名失败";
        //报名
        OActivityMember member = this.convertoAcMember(activityId, oCommonMember.getUserId(), req);
        if(!checkActivityMember(member, resp)){
            return;
        }
        member.setNickname(user.getNickname());
        if (activity.getMaxJoin() > 0 && activity.getJoinNum() >= activity.getMaxJoin()) {
            message = "报名人数已满，请联系管理员！";
        } else {
            if (oActivityService.createActityMember(member) > 0) {
                message = "已提交报名资料，请等待管理员审核。";
                //给管理员发送审核消息
                OClub club = oClubService.findValidClub(activity.getOClubId());
                if (club != null) {
                    List<OCommonMember> listMember = oMemberService.listAdmin(club.getOClubId());
                    String activityUrl = oMessageService.getOActivityLink(club.getUrl(), activityId, activity.getTitle());
                    if (club != null && listMember != null && !listMember.isEmpty()) {
                        for (OCommonMember adminMember : listMember) {// 给管理员发消息
                            oMessageService.sendSysMsg(adminMember.getUserId(), OMessageService.ACTIVITY_APPLY, activityUrl, member.getName());
                        }
                    }
                }
                printMsg(resp, Result.success(message));
                return;
            }
        }
        printMsg(resp, Result.error(message));
    }

    /**
     * 取消活动报名
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/cancelApplyActivity.do", method = RequestMethod.POST)
    public void cancelApplyActivity(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        OActivity activity = oActivityService.findById(OActivity.class, activityId);
        if (activity == null) {
            printMsg(resp, Result.dataError("活动不存在"));
            return;
        }
        User user = checkUser(req, resp);
        if (user == null) {
            return;
        }
        OCommonMember oCommonMember =  oMemberService.findCommonMember(user.getUid(), activity.getoClubId());
        if (oCommonMember == null) {
            printMsg(resp, Result.error("您不是该车友会会员"));
            return;
        }
        OActivityMember oActivityMember = oActivityService.findActivityMember(activityId, user.getUid());
        if (oActivityMember == null) {
            printMsg(resp, Result.error("您没申请加入该活动或被拒绝"));
            return;
        }
        if (oActivityMember.getStatus() == OActivityMember.STATUS_PASS) {
            if (activity.getSignupDate().getTime() <= DateUtils.getNow().getTime()) {
                printMsg(resp, Result.error("报名时间已截止，不能取消报名"));
                return;
            }
        }
        //存在记录则为取消报名
        if (oActivityService.deleteActivityMember(activityId, user.getUid()) > 0) {
            oActivityService.updateActivityJoinNum(activityId);
            printMsg(resp, Result.success("取消成功"));
        } else {
            printMsg(resp, Result.dataError("取消失败"));
        }
    }

    /**
     * 导出活动报名人员清单
     *
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/exportActivityMember.do")
    public String exportActivityMember(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        OActivity activity = oActivityService.findById(OActivity.class, activityId);
        OClub club = oClubService.findValidClub(oClubId);
        if (activityId < 1 || club == null || activity == null) {
            return redirect404(resp);
        }
        if (!isAdmin(req, resp)) {
            return PAGE_NO_AUTH;
        }
        List<OActivityMember> listMember = oActivityService.listMember(activityId, OActivityMember.STATUS_PASS);
        List<Map<String, Object>> rows = new ArrayList(listMember.size());
        int i = 0;
        int num = 0;
        for (OActivityMember a : listMember) {
            HashMap<String, Object> row = new HashMap<String, Object>();
            row.put("编号", ++i);
            row.put("论坛昵称", a.getNickname());
            row.put("姓名", null == a.getName() ? "" : a.getName());
            row.put("电话", null == a.getPhone() ? "" : a.getPhone());
            row.put("参加人数", 0 == a.getJoinNum() ? "" : a.getJoinNum());
            num += a.getJoinNum();
            row.put("车牌号", null == a.getLicencePlate() ? "" : a.getLicencePlate());
            row.put("备注", null == a.getRemark() ? "" : a.getRemark());
            row.put("加入时间", null == a.getCreateAt() ? "" : DateUtils.format(a.getCreateAt()));
            rows.add(row);
        }
        List<String> cols = Arrays.asList("编号", "论坛昵称", "姓名", "电话", "参加人数", "车牌号", "备注", "加入时间");
        //统计
        HashMap<String, Object> total = new HashMap<String, Object>();
        total.put("编号", String.format("共计%s人", i));
        total.put("参加人数", String.format("共计%s人", num));
        rows.add(total);
        printExcelFile(resp, "activity_userList", rows, cols);
        return null;
    }

    /**
     * 活动表单验证
     *
     * @param activity
     * @param resp
     * @
     */
    private boolean checkActivity(OActivity activity, HttpServletResponse resp) {
        String nameMsg = this.checkName(activity.getTitle());
        if (StringUtils.isBlank(activity.getPicUrl()) || (activity.getPicUrl().equals(defalutImg))) {
            printMsg(resp, Result.dataError("请上传活动封面图"));
            return false;
        } else if (!nameMsg.equals("true")) {
            printMsg(resp, Result.dataError(nameMsg));
            return false;
        } else if (activity.getBeginDate() == null) {
            printMsg(resp, Result.dataError("请选择活动开始时间"));
            return false;
        } else if (activity.getEndDate() == null) {
            printMsg(resp, Result.dataError("请选择活动结束时间"));
            return false;
        } else if (activity.getSignupDate() == null) {
            printMsg(resp, Result.dataError("请选择活动报名截止时间"));
            return false;
        } else if (activity.getJoinNum() < 0) {
            printMsg(resp, Result.dataError("活动费用不能小于0"));
            return false;
        } else if (activity.getContent().length() < 5) {
            printMsg(resp, Result.dataError("活动内容长度不能小于5"));
            return false;
        }
        return true;
    }

    /**
     * 对象转换
     *
     * @param req
     * @return
     */
    private OActivity convertActivity(HttpServletRequest req) {
        OActivity activity = new OActivity();
        activity.setActivityId(WebUtils.paramLong(req, "activityId", 0));
        activity.setOClubId(WebUtils.paramLong(req, "oClubId", 0));
        activity.setTitle(WebUtils.param(req, "title", "").trim());
        String content = WebUtils.param(req, "content", "").trim();
        activity.setContent(content);
        activity.setFullContent(WebUtils.param(req, "content", "").trim());
        activity.setBeginDate(WebUtils.parseDate(req, "beginDate"));
        activity.setEndDate(WebUtils.parseDate(req, "endDate"));
        activity.setSignupDate(WebUtils.parseDate(req, "signupDate"));
        activity.setLongContent(content.length() > OActivity.CONTENT_LENGTH ? OActivity.HAS_LONGCONTENT : OActivity.NOTHAS_LONGCONTENT);
        activity.setOnlineStatus(WebUtils.paramInt(req, "onlineStatus", 0));
        activity.setProvinceId(WebUtils.paramInt(req, "provinceId", 0));
        activity.setProvinceName(WebUtils.param(req, "provinceName", "").trim());
        activity.setCityId(WebUtils.paramInt(req, "cityId", 0));
        activity.setCityName(WebUtils.getAreaPlaceByReq(req, "cityName", ""));
        activity.setMoney(WebUtils.paramInt(req, "money", 0));
        activity.setPicUrl(WebUtils.param(req, "picUrlOrigin", "").trim());
        activity.setJoinNum(WebUtils.paramInt(req, "joinNum", 0));
        activity.setMaxJoin(WebUtils.paramInt(req, "maxJoin", 0));
        activity.setCreateBy(WebUtils.paramInt(req, "createBy", 0));
        activity.setCreateAt(WebUtils.parseDate(req, "createAt"));
        activity.setStatus(OActivity.STATUS_YES);
        return activity;
    }

    /**
     * 活动申请表单验证
     *
     * @param member
     * @param resp
     * @return
     * @
     */
    private boolean checkActivityMember(OActivityMember member, HttpServletResponse resp) {
        if (StringUtils.isBlank(member.getName())) {
            printMsg(resp, Result.dataError("请输入真实姓名"));
            return false;
        } else if (member.getName().length() > 20) {
            printMsg(resp, Result.dataError("姓名长度不能超过20"));
            return false;
        } else if (StringUtils.isBlank(member.getPhone())) {
            printMsg(resp, Result.dataError("请输入联系电话"));
            return false;
        } else if (member.getPhone().length() > 20) {
            printMsg(resp, Result.dataError("电话长度不能超过20"));
            return false;
        } else if(!member.getPhone().matches(Regex.number.value)){
            printMsg(resp, Result.dataError("请输入正确的联系电话"));
            return false;
        }else if (member.getJoinNum() < 1) {
            printMsg(resp, Result.dataError("请输入正确的人数"));
            return false;
        } else if (member.getLicencePlate().length() > 20) {
            printMsg(resp, Result.dataError("车牌长度不能超过20"));
            return false;
        }else if (member.getRemark().length() > 255) {
            printMsg(resp, Result.dataError("备注长度不能超过255"));
            return false;
        }
        return true;
    }

    private OActivityMember convertoAcMember(long activityId, long userId, HttpServletRequest req) {
        OActivityMember activityMember = new OActivityMember();
        activityMember.setActivityId(activityId);
        activityMember.setUserId(userId);
        activityMember.setName(WebUtils.param(req, "name", "").trim());
        activityMember.setPhone(WebUtils.param(req, "phone", "").trim());
        activityMember.setJoinNum(WebUtils.paramInt(req, "joinNum", 0));
        activityMember.setLicencePlate(WebUtils.param(req, "lincensePlate", "").trim());
        activityMember.setRemark(WebUtils.param(req, "remark", "").trim());
        activityMember.setCreateAt(DateUtils.getNow());
        activityMember.setStatus(OActivityMember.STATUS_APPLY);
        return activityMember;
    }

    /**
     * 报名参加活动对象转jsonArray
     *
     * @param list
     * @return
     */
    public JSONArray acitivityToJson(List<OActivityMember> list, long oClubId, int sourceAgent) {
        JSONArray jsonArray = new JSONArray();
        if (list != null && !list.isEmpty()) {
            for (OActivityMember member : list) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", EncodeUtils.encodeForHTML(member.getName(), sourceAgent));
                jsonObject.put("nickname", EncodeUtils.encodeForHTML(member.getNickname(), sourceAgent));
                jsonObject.put("joinNum", member.getJoinNum());
                jsonObject.put("phone", EncodeUtils.encodeForHTML(member.getPhone(), sourceAgent));
                jsonObject.put("remark", member.getRemark());
                jsonObject.put("lincensePlate", member.getLicencePlate());
                OCommonMember clubMember = oMemberService.findCommonMember(member.getUserId(), oClubId);
                String url = "";
                long uid = 0;
                if (clubMember != null) {
                    url = systemConfig.getUcRoot() + "/" + clubMember.getUserId() + "/";
                    uid = clubMember.getUserId();
                }
                jsonObject.put("userId", uid);
                jsonObject.put("memberId", member.getUserId());
                jsonObject.put("pic", url);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }

    /**
     * 活动名称验证
     *
     * @param name
     * @return
     */
    public String checkName(String name) {
        if (StringUtils.isBlank(name)) {
            return "请输入活动名称";
        } else if (StringUtil.length(name) > 60) {
            return "最多30个字";
        } else {
            return "true";
        }
    }

    /**
     * 活动名称动态验证
     *
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/checkActivityName.do", method = RequestMethod.POST)
    public void checkActivityName(HttpServletRequest req, HttpServletResponse resp) {
        WebUtils.setEncoding(req, resp);
        String name = WebUtils.param(req, "name", "");
        String retNameMsg = this.checkName(name);
        int code = -1;
        String msg;
        if (!"true".equals(retNameMsg)) {
            msg = retNameMsg;
        } else {
            code = 1;
            msg = "验证通过";
        }
        printMsg(resp, Result.instance().set("code", code).set("message", msg));
    }

    /**
     * 获取活动状态 status 0:接受报名，1：报名已截止，2；活动已开始， －1：活动已经结束
     */
    private int getActivityStatus(OActivity activity) {
        Date now = DateUtils.getNow();
        if (!now.after(activity.getEndDate())) {//活动还没结束
            if ((now.getTime() <= activity.getSignupDate().getTime())) { //活动未开始 且 报名未结束
                return 0;
            } else if (activity.getSignupDate().getTime() < now.getTime() && activity.getBeginDate().getTime() > now.getTime()) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return -1;
        }
    }

    /**
     * 是否可以加入活动
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/isJoinActivity")
    @ResponseBody
    public void isJoinActivity(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        long activityId = WebUtils.paramLong(request, "activityId", 0);
        long userId = WebUtils.paramLong(request, "userId", 0);
        OActivity activity = oActivityService.findById(OActivity.class, activityId);
        if (activity != null) {
            Result rs = oActivityService.getActivityStatusDesc(userId, activity);
            printMsg(response, Result.success(rs));
        } else {
            printMsg(response, Result.dataError("找不到该活动"));
        }
    }

    /**
     * 管理活动页
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/editActivity.do", method = RequestMethod.GET)
    public String editActivity(HttpServletRequest req, HttpServletResponse resp) {
        long activityId = WebUtils.paramLong(req, "activityId", 0);
        long oClubId = WebUtils.paramLong(req, "oClubId", 0);
        OClub oClub = oClubService.findValidClub(oClubId);
        if (oClub == null) {
            return redirect404(resp);
        }
        OActivity oActivity = oActivityService.findValidActivity(activityId);
        if (oActivity == null) {
            return redirect404(resp);
        }
        if (!isAdmin(req, resp)) {
            return null;
        }
        //完整内容
        if (oActivity.getLongContent() == OActivity.HAS_LONGCONTENT) {
            oActivity.setFullContent(oActivityService.getActivityContent(oActivity.getActivityId()));
        } else {
            oActivity.setFullContent(oActivity.getContent());
        }
        req.setAttribute("activity", oActivity);
        req.setAttribute("oClub", oClub);
        return "template/official/pc/activity/activityAdd";
    }
}
